<?php

namespace api\services\order;

use common\models\order\OrderModel;
use api\extensions\ApiBaseService;
use api\services\wechat\MiniPayService;
use common\models\order\OrderGoodsModel;
use common\services\goods\GoodsStockService;
/**
 * 支付服务
 */
class PaymentService extends ApiBaseService
{

    /**
     * 订单支付
     * @param array $params 请求参数
     * * */
    public static function payment($params)
    {
        try {
            $user = \Yii::$app->user->getInfo();
            $order = OrderModel::findOne(['order_sn' => $params['order_sn'], 'user_id' => $user['id']]);
            if (empty($order)) {
                throw new \Exception('订单信息异常');
            }
            if ($order['state'] != OrderModel::STATE_WAIT_PAY) {
                throw new \Exception('订单状态异常');
            }
            return MiniPayService::minipay($order, $user['openid']);
        } catch (\Exception $exc) {
            \Yii::$app->writeLog->log('/api/pay', '支付回调结果', ['message' => $exc->getMessage()], 'INFO');
            return self::jsonError($exc->getMessage());
        }
    }

    /**
     * 支付回调
     * **/
    public static function callback($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $order_sn = $params['order_sn'];
            // 查找订单信息
            $order = OrderModel::findOne(['order_sn' => $order_sn]);
            if (empty($order)) {
                throw new \Exception('订单信息异常');
            }
            // 手动触发支付查询
            if (isset($params['query']) && $params['query'] == 1 && $order['state'] == OrderModel::STATE_WAIT_RECEIVE) {
                return self::jsonSuccess($order);
            }
            if ($order['state'] != OrderModel::STATE_WAIT_PAY) {
                throw new \Exception('订单状态异常');
            }
            //查询
            $query = MiniPayService::query($params['order_sn']);
            if ($query['code'] == 201) {
                throw new \Exception($query['message']);
            }
            // 更新订单状态
            $order->setAttributes(['state' => OrderModel::STATE_WAIT_DELIVERY, 'pay_time' => date('Y-m-d H:i:s')], false);
            if (empty($order->save())) {
                throw new \Exception('更新异常');
            }
            //处理业务
            // $res = self::otherBusiness($order, $params);
            // if ($res['code'] == 201) {
            //     throw new \Exception('更新异常');
            // }
            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            $transaction->rollBack();
            \Yii::$app->writeLog->log('/api/callback', '支付回调异常', ['params' => $params, 'message' => $exc->getMessage(), 'line' => $exc->getLine()], 'INFO');
            return self::jsonError($exc->getMessage());
        }
    }

    /**
     * 支付确认
     * **/
    public static function confirm($params)
    {
        $params['query'] = 1;
        return self::callback($params);
    }

}
